package org.lewis.common.jobs;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

public class CronTriggerHelper {
	
	private Log log = LogFactory.getLog(CronTriggerHelper.class);
	
	private SchedulerFactory sf = new StdSchedulerFactory();
	
	private Scheduler sched;
	
	public CronTriggerHelper(){
		log.info("------- Initializing -------------------");
        try {
			this.sched=sf.getScheduler();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
        log.info("------- Initialization Complete --------");
	}
	
	 public void stop() throws Exception {
		 if(null!=sched){
			 sched.shutdown(true);
		 }
	 }

    public void run() throws Exception {
        log.info("------- Scheduling Jobs ----------------");
        JobDetail job = newJob(SendEmailJob.class).withIdentity("job1", "group1").build();
        CronTrigger trigger = newTrigger().withIdentity("trigger1", "group1").withSchedule(cronSchedule("0/5 * * * * ?")).build();
        Date ft = sched.scheduleJob(job, trigger);
        log.info(job.getKey() + " has been scheduled to run at: " + ft+ " and repeat based on expression: "+ trigger.getCronExpression());
        log.info("------- Starting Scheduler ----------------");
        sched.start();
    }

}
